package com.joysuccess.bacnet.config;

import com.joysuccess.common.utils.HelpUtils;
import com.serotonin.bacnet4j.LocalDevice;
import com.serotonin.bacnet4j.exception.BACnetException;
import com.serotonin.bacnet4j.npdu.ip.IpNetwork;
import com.serotonin.bacnet4j.transport.Transport;
import com.serotonin.bacnet4j.type.constructed.Address;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @author zhangqing
 */
@Configuration
public class BacnetConfig {

    private final static Logger LOGGER = LoggerFactory.getLogger(BacnetConfig.class);

    @Value("${bacnet.remote-server-list:null}")
    private String bacnetRemoteServerList;

    private String comma = ", ";
    private String colon = ":";

    /**
     * 获取本地设备，包括：初始化、加载远程设备列表
     * @return
     * @throws Exception
     */
    @Bean("localDevice")
    public LocalDevice getLocalDevice() throws Exception {
        //获取本地设备
        LocalDevice localDevice =this.initLocalDevice();
        //加载远程设备
        initiRemotBacnetServerList(localDevice);
        return localDevice;
    }

    /**
     * 初始化本地设备
     * @return
     * @throws Exception
     */
    public LocalDevice initLocalDevice() throws Exception {
        IpNetwork network = new IpNetwork(IpNetwork.DEFAULT_BROADCAST_IP, IpNetwork.DEFAULT_PORT + 1);
        Transport transport = new Transport(network);
        LocalDevice localDevice = new LocalDevice(1, transport);
        localDevice.initialize();
        LOGGER.info("Initializing local Device initialize success====");
        return localDevice;
    }

    /**
     * 加载远程设备
     * @param localDevice
     */
    public  void initiRemotBacnetServerList(LocalDevice localDevice) {
        if(HelpUtils.isNotEmpty(bacnetRemoteServerList)) {
            if(bacnetRemoteServerList.indexOf(comma) > 0) {
                String [] remotesList =bacnetRemoteServerList.split(comma);
                if(HelpUtils.isNotEmpty(remotesList)) {
                    for (int i = 0; i < remotesList.length; i++) {
                        splitIniteRemotsList(localDevice,remotesList[i]);
                    }
                }
            }else {
                splitIniteRemotsList(localDevice,bacnetRemoteServerList);
            }
        }
    }

    /**
     * 解析每个设备的ip和唯一编号,并且进行初始化
     * @param localDevice
     * @param remoteServer
     */
    public void splitIniteRemotsList(LocalDevice localDevice,String remoteServer) {
        String [] remotes =StringUtils.split(remoteServer,colon);
        try {
            if(HelpUtils.isNotEmpty(remotes)) {
                this.addRemoteDevice(localDevice,remotes[0],Integer.parseInt(remotes[1]));
                LOGGER.info(remoteServer + " add to local device success====");
            }else {
                LOGGER.info(remoteServer + " add to local device error!!!!!!====");
            }
        } catch (BACnetException e) {
            e.printStackTrace();
            LOGGER.info("Bacnet Error:启动失败，添加远程设备出现错误，检查ip地址和设备唯一编号：ip = " + remotes[0] + " remoteDeviceIdentifier = " + remotes[1]);
//            System.exit(0);
        }
    }

    /**
     * 给localDevice对象添加远程设备
     * @param localDevice
     * @param remoteDeviceIpAddress
     * @param remoteDeviceIdentifier
     * @throws BACnetException
     */
    public void addRemoteDevice(LocalDevice localDevice, String remoteDeviceIpAddress, int remoteDeviceIdentifier) throws BACnetException {
        localDevice.findRemoteDevice(new Address(remoteDeviceIpAddress, IpNetwork.DEFAULT_PORT), null, remoteDeviceIdentifier);
    }
}
